

ifeq ($(OS),Windows_NT)
export ICE_TOOLS_BIN=d:/msys64/mingw64/bin/
export ICESPROG = tools/icesprog 
else
export ICE_TOOLS_BIN=
export ICESPROG = icesprog 
endif 


# 中断入口地址 
CODE_INTERRUPT_VECTOR=7FF
# 代码空间大小
CODE_SZIE=2048

FCHAI=fchai

rtl_src = ../rtl/top.v 
pcf_file = io.pcf


ICELINK_DIR = $(shell df | grep iCELink | awk '{print $$6}')
${warning iCELink path: $(ICELINK_DIR)}
ICELINK_DIR = H:/

# ifeq '$(findstring ;,$(PATH))' ';'
#     detected_OS := Windows
# else
#     detected_OS := $(shell uname 2>/dev/null || echo Unknown)
#     detected_OS := $(patsubst CYGWIN%,Cygwin,$(detected_OS))
#     detected_OS := $(patsubst MSYS%,MSYS,$(detected_OS))
#     detected_OS := $(patsubst MINGW%,MSYS,$(detected_OS))
# endif


all:clean soft_led synth 12M prog_flash 

synth:rtl 
	@sed -i 's/`define PSM_CODE_SIZE.*/`define PSM_CODE_SIZE $(CODE_SZIE)/g' rtl/top.v
	mkdir -p build 
	cp *.pcf build 
	cd build && $(ICE_TOOLS_BIN)yosys -p "synth_ice40 -json synth.json -blif synth.blif "  $(rtl_src)
ifeq ($(OS),Windows_NT)
	cd build && $(ICE_TOOLS_BIN)nextpnr-ice40 --lp1k --package cm36 --json synth.json --pcf $(pcf_file) --asc synth.asc --freq 36
else 
	cd build && arachne-pnr -d 1k -P cm36 -p $(pcf_file)  synth.blif -o synth.asc
endif
	cd build && $(ICE_TOOLS_BIN)icepack synth.asc synth.bin 


debug:
	./Serial.chai

prog_flash:
	$(ICESPROG) build/synth.bin

copy_flash:
	@echo "$(ICELINK_DIR)"
	@if [ -d '$(ICELINK_DIR)' ]; \
    then \
        cp build/synth.bin $(ICELINK_DIR); \
		echo "copy done" ;\
    else \
        echo "iCELink not found"; \
        exit 1; \
    fi

# 设置时钟频率
8M:
	$(ICESPROG) -c 1

12M:
	$(ICESPROG) -c 2

36M:
	$(ICESPROG) -c 3

72M:
	$(ICESPROG) -c 4


udp: 
	$(FCHAI) ./tools/upload.chai 

ys:
	mkdir -p build 
	cp *.ys build  && cd build && $(ICE_TOOLS_BIN)yosys synth.ys 


sim:
	@mkdir -p build
	@iverilog  -o build/tb.vvp   -I ./rtl/ ./rtl/tb.v 
	@cd build && vvp tb.vvp



clean:
	rm -rf build


# build:
# 	yosys -p "synth_ice40 -blif $(filename).blif" $(filename).v
# 	nextpnr-ice40 --lp1k --package cm36 --json $(filename).json --pcf $(pcf_file) --asc $(filename).asc --freq 48
# 	# arachne-pnr -d 1k -P cm36 -p $(pcf_file)  $(filename).blif -o $(filename).asc
# 	icepack $(filename).asc $(filename).bin

# prog_flash:
# 	@echo "$(ICELINK_DIR)"
# 	@if [ -d '$(ICELINK_DIR)' ]; \
#         then \
#             cp $(filename).bin $(ICELINK_DIR); \
#         else \
#             echo "iCELink not found"; \
#             exit 1; \
#     fi


include firmware.mk

include pblaze.mk

